<template>
  <div class="Line-chart-sales">
    <div class="date-select">
      <el-text tag="b" size="large" class="date-select-el-text">销售额趋势</el-text>
      <el-date-picker
        v-model="dataSelect"
        type="daterange"
        range-separator="至"
        start-placeholder="开始日期"
        end-placeholder="结束日期"
        value-format="x"
        @change="changeDataSelect"
      />
    </div>
    <div id="lineChart" style="width: 100%; height: 300px"></div>
  </div>
</template>

<script setup lang="ts">
import { ref, watch } from "vue";
import type { EChartsOption } from "@/config/echarts";
import {echarts} from "@/config/echarts";
import type { salesDrendRes } from "@/types/index";
import { salesDrendApi } from "@/api/api";
interface Props {
  data: salesDrendRes;
}
const propsData = defineProps<Props>();
const optionData = ref();
let chartEvent: any = null;
watch(propsData, (newval) => {
  var myChart = echarts.init(document.getElementById("lineChart"));
  chartEvent = myChart;
  var option: EChartsOption;
  window.addEventListener("resize", function () {
    myChart.resize(); //跟随浏览器改变尺寸
  });
  option = {
    grid: [
      {
        left: 30,
        top: 20,
        right: 0,
        bottom: 30,
      },
    ],
    tooltip: {
      trigger: "axis",
    },
    xAxis: {
      type: "category",
      data: newval.data.time,
    },
    yAxis: {
      type: "value",
    },
    series: [
      {
        data: newval.data.total,
        type: "line",
        name: "销售额",
      },
    ],
  };
  optionData.value = option;
  option && myChart.setOption(option);
});
// 选择的日期
const dataSelect = ref<number[]>([]);
// 选择日期时触发
async function changeDataSelect(params: number[]) {
  dataSelect.value = params;
  const res = await salesDrendApi({ queryTime: params });
  optionData.value.xAxis.data = res.data.time;
  optionData.value.series[0].data = res.data.total;
  chartEvent.setOption(optionData.value);
}
</script>

<style scoped>
.Line-chart-sales {
  grid-column: span 2;
}
.date-select {
  display: flex;
  align-items: center;
  height: 32px;
}
.date-select-el-text {
  flex: 1;
}
</style>
